package com.zhanglijie.improve.aqs.exclusive.test;

import java.util.concurrent.locks.Condition;

import com.zhanglijie.improve.aqs.exclusive.MyReentrantLock;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/10/19 0019 22:34
 */
public class MyReentrantLockAwaitAndSignal {
    public static void main(String[] args) throws InterruptedException {
        MyReentrantLock myReentrantLock = new MyReentrantLock();
        Condition condition = myReentrantLock.newCondition();
        Thread t1 = new Thread(() -> {
            myReentrantLock.lock();
            try {
                System.out.println(Thread.currentThread()
                    .getName() + "开始执行任务   ");
                Thread.sleep(1000);
                System.out.println(Thread.currentThread()
                    .getName() + "睡了一秒后即将阻塞");
                condition.await();
                System.out.println(Thread.currentThread()
                    .getName() + "被正常唤醒可能是signal|interrupt唤醒的===》其实中断这个业务代码不会执行直接进入下面的catch代码块 但是signal会执行这个业务代码");

                if(Thread.currentThread().isInterrupted()){
                    System.out.println(Thread.currentThread()
                        .getName() +"被signal唤醒了 但是 中断也触发了");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                myReentrantLock.unlock();
            }
        }, "t1");
        t1.start();

        Thread.sleep(1000);
        //
        // new Thread(()->{
        //     myReentrantLock.lock();
        //     try{
        //         System.out.println(Thread.currentThread().getName()+"拿到锁 将通过signal方式唤醒t1线程");
        //         condition.signal();
        //     }catch (Exception e){
        //         e.printStackTrace();
        //     }finally {
        //         myReentrantLock.unlock();
        //     }
        // },"t2").start();




        new Thread(()->{
            //myReentrantLock.lock();中断不需要锁
            try{
                System.out.println(Thread.currentThread().getName()+"拿到锁 将通过interrupt方式唤醒t1线程");
                t1.interrupt();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                //myReentrantLock.unlock();
            }
        },"t3").start();
    }
}
